package cn.shop.utils;

import cn.hutool.core.lang.Dict;
import cn.hutool.crypto.SecureUtil;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author jzw
 * @since 2021-12-13 16:41
 */
public class PayUtil {

	/**
	 * 生成签名
	 */
	public static String getSignToken(Dict map, String appKey) {

		String result = "";
		try {
			Set<Entry<String, Object>> infoIds = map.entrySet();
			// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
			List<Entry<String, Object>> collect = infoIds.stream().sorted((o1, o2) -> (o1.getKey()).toString().compareTo(o2.getKey())).collect(Collectors.toList());
			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, Object> item : collect) {
				String key = item.getKey();
				Object val = item.getValue();
				if (val != null) {
					sb.append(val).append("&");
				}
			}
			sb.append(appKey);
			String data = sb.toString();
			result = SecureUtil.md5(data);
		} catch (Exception e) {
			return null;
		}
		return result;
	}

}
